<?php
/**
 * Created by PhpStorm .
 * User: {Administrator}
 * Date: {2022/7/6 16:37}
 * Author: '树叶'
 * Email: 'ayunu@qq.com'
 * Motto Info: '理想如果不向现实做一点点屈服，那么理想也将归于尘土。'
 */

namespace app\api\model;
use Monolog\Handler\IFTTTHandler;
use PhpOffice\PhpSpreadsheet\Cell\DataValidation;
use think\Db;
use think\Model;
use app\api\model\UserHistory as UserHistoryModel;
use app\api\model\GoodsItem as GoodsItemModel;
use app\api\model\Config as ConfigModel;
use app\api\model\User as UserModel;
use wxpay\Wechat;

class Order extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = '';
    protected $resultSetType = 'collection';
    // 追加属性
    protected $append = [

    ];

    /**
     * @param $uid 用户id
     * @param $cart_id 购物车id
     * @param $item_id 商品规格id
     * @param $goods_num 商品数量
     * @param $collocation 是否搭配 是否使用;0-不使用,1使用
     * @param $type 类型;1-购物车,0立即购买
     */
    public static function add($uid, $cart_id = 0, $item_id = 0, $goods_num = 1, $collocation = 0, $type = 0,$money=0)
    {
        $result = [
            'data'   => [
                'list' => [], //商品数据
                'postage' => 0, //邮费
                'smallclothes_amout' => 0,  //商品件数
                'order_amout'    => 0,  //优惠
                'original_price' => 0,  //原价
                'user_integral'  => 0, //积分
                'collocation'    => '', //搭配
                'type'           => $type, //
                'freight'        => 0, //

            ],
            'msg'     => '',
            'status'  => false,
        ];
        $UserModel   = new UserModel();
        $userdata    = $UserModel->getUserInfo($uid); // 用户信息

        $ConfigModel = new ConfigModel();
        $angent      = $ConfigModel->getAgent(); //普通代理商
        $OneAgent    = $ConfigModel->getOneAgent(); //超级代理商
        $num         = 0;  //商品总数量
        $num_price   = 0; //商品总金额
        $postage_price = 0; //运费
        $order_amout = 0; //优惠
        $list = []; // 商品信息
        if ($type) // 如果是从购物车来的
            {
                //查询购物车的商品
                $where_cart = [];
                $where_cart['id']  = ['in',$cart_id];
                $where_cart['uid'] = ['eq',$uid];
                $goods_cart = Db::name('goods_cart')
                    ->where($where_cart)
                    ->select();

                if (empty($goods_cart))
                {
                    $result['msg'] = '购物车不存在';
                    return $result;
                }

                foreach ($goods_cart as $car_key => $car_val)
                {

                    // 获取商品信息
                    if ($car_val['sku_id'])
                    {
                        $goods = Db::name('goods_item')
                            ->alias('it')
                            ->join('goods g','g.id = it.goods_id','LEFT')
                            ->field('it.id,it.goods_id,g.goods_number,g.partnumber,g.name,g.freight,g.free_shipping,g.free_shipping,it.spec_value_str,g.main_image,it.ordinaryprice,it.haveprice,it.agentprice')
                            ->where('it.goods_id',$car_val['gid'])
                            ->where('it.id',$car_val['sku_id'])
                            ->find(); //获取商品规格的商品
                        $goods['sku_id'] = $goods['id'];
                        $goods['id'] = $goods['goods_id'];
                        unset($goods['goods_id']);
                    }else{
                        $goods = Db::name('goods')->field('id,goods_number,partnumber,name,freight,free_shipping,main_image,ordinaryprice,haveprice,agentprice')
                            ->where('id',$car_val['gid'])->find();
                    }


                    // 获取商品价格
                    if ($userdata['is_vip'] == 0)
                    {
                        $goods['price'] = $goods['ordinaryprice'];
                    }elseif ($userdata['is_vip'] == 1){
                        $goods['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : $goods['haveprice'];
                    }elseif ($userdata['is_vip'] == 2){
                        if ($userdata['data']['is_price'] == 1)
                        {
                            $goods['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : bcmul($goods['haveprice'], $angent, 2);
                        }else{
                            $goods['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : $goods['haveprice'];
                        }
                    }elseif ($userdata['is_vip'] == 3){
                        if ($userdata['data']['is_price'] == 1)
                        {
                            $goods['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : bcmul($goods['haveprice'], $OneAgent, 2); //商品价格
                        }else{
                            $goods['price'] = $goods['agentprice'] != 0 ? $goods['agentprice'] : $goods['haveprice'];
                        }
                    }
                    $goods['num']   = $car_val['goods_num'];
                    $goods['zong_price'] = bcmul($goods['price'], $car_val['goods_num'], 2); // 每个商品总价
                    $num_price  += $goods['zong_price']; // 支付价格
                    $num        += $car_val['goods_num']; // 商品总数量
                    $list[]     = $goods; //每个商品
                }
            }else{
                 $cart_id = explode(",",$cart_id);
                 $goods = Db::name('goods')
                    ->where('id',"in",$cart_id)
                    ->field('id,name,main_image,partnumber,ordinaryprice,haveprice,agentprice,integral_num,freight,free_shipping,spec_type,stock,goods_number')
                    ->select();
                foreach ($goods as $k=>$good){
                    // dump(111);
                    // die;
                     if ($good['spec_type'] == 1)
                     {
                        // 多规格
                         if ($item_id == 0)
                         {
                            $result['msg'] = '请选择规格';
                            return $result;
                         }
    
                         $goodsitem = Db::name('goods_item')
                             ->field('id,image,ordinaryprice,haveprice,agentprice')
                             ->where('id',$item_id)
                            //  ->where('goods_id',$cart_id)
                            ->where('goods_id',$good["id"])
                             ->find();
                         if (empty($goodsitem))
                         {
                             $result['msg'] = '该规格不是此商品的';
                             return $result;
                         }
                         $goods[$k]['ordinaryprice'] = $goodsitem['ordinaryprice'];
                         $goods[$k]['haveprice']     = $goodsitem['haveprice'];
                         $goods[$k]['agentprice']    = $goodsitem['agentprice'];
                         $goods[$k]['sku_id']        = $goodsitem['id'];
                         $goods[$k]['main_image']    = $goodsitem['image'];
                     }
                    
                    if ($userdata['is_vip'] == 0)
                    {
                        $goods[$k]['price'] = $good['ordinaryprice'];
                    }elseif ($userdata['is_vip'] == 1){
    
                        $goods[$k]['price'] = $good['agentprice'] != 0 ? $good['agentprice'] : $good['haveprice'];
                    }elseif ($userdata['is_vip'] == 2){
                        if ($userdata['data']['is_price'] == 1)
                        {
                            $goods[$k]['price'] = $good['agentprice'] != 0 ? $good['agentprice'] : bcmul($good['haveprice'], $angent, 2);
                        }else{
                            $goods[$k]['price'] = $good['agentprice'] != 0 ? $good['agentprice'] : $good['haveprice'];
                        }
                    }elseif ($userdata['is_vip'] == 3){
                        if ($userdata['data']['is_price'] == 1)
                        {
                            $goods[$k]['price'] = $good['agentprice'] != 0 ? $good['agentprice'] : bcmul($good['haveprice'], $OneAgent, 2);
                        }else{
                            $goods[$k]['price'] = $good['agentprice'] != 0 ? $good['agentprice'] : $good['haveprice'];
                        }
                    }
    
                    $goods[$k]['num'] = $goods_num; // 商品数量
                    $num = $goods_num; //商品数量
                    $num_price = bcmul($goods[$k]['price'], $num, 2); //商品金额
                    $goods[$k]['zong_price'] = $num_price; //商品总金额
                }
                if ($collocation) // 如果勾选搭配商品
                {
                    $goods_collocation = Db::name('goods_collocation')->where('id',$collocation)->find();

                        if ($goods_collocation['child_goods_sku'])
                        {
                            $goods_dp = Db::name('goods_item')
                                ->field('id,goods_id,ordinaryprice,haveprice,agentprice')
                                ->where('id',$goods_collocation['child_goods_sku'])
                                ->find();
                            $goods_dp['sku_id'] = $goods_dp['id'];
                            $goods_dp['id']     = $goods_dp['goods_id'];
                            unset($goods_dp['goods_id']);
                        }else{
                            $goods_dp = Db::name('goods')
                                ->field('id,name,ordinaryprice,haveprice,agentprice')
                                ->where('id',$goods_collocation['child_goods_id'])
                                ->find();
                        }
                        if ($userdata['is_vip'] == 0)
                        {
                            $goods_dp['price'] = $goods_dp['ordinaryprice'];
                        }elseif ($userdata['is_vip'] == 1){
                            $goods_dp['price'] = $goods_dp['agentprice'] != 0 ? $goods_dp['agentprice'] : $goods_dp['haveprice'];
                        }elseif ($userdata['is_vip'] == 2){
                            if ($userdata['data']['is_price'] == 1)
                            {
                                $goods_dp['price'] = $goods_dp['agentprice'] != 0 ? $goods_dp['agentprice'] : bcmul($goods_dp['haveprice'], $angent, 2);
                            }else{
                                $goods_dp['price'] = $goods_dp['agentprice'] != 0 ? $goods_dp['agentprice'] : $goods_dp['haveprice'];
                            }
                        }elseif ($userdata['is_vip'] == 3){
                            if ($userdata['data']['is_price'] == 1)
                            {
                                $goods_dp['price'] = $goods_dp['agentprice'] != 0 ? $goods_dp['agentprice'] : bcmul($goods_dp['haveprice'], $OneAgent, 2);
                            }else{
                                $goods_dp['price'] = $goods_dp['agentprice'] != 0 ? $goods_dp['agentprice'] : $goods_dp['haveprice'];
                            }
                        }


                    $price = $goods_dp['price'] + $num_price;  //搭配的价格+商品的总金额 =$pric 两个的价格
                    $num_price = bcsub($price, $goods_collocation['preferential'], 2); // 在用两个商品的价格减去 搭配优惠的价格 = 商品支付的价格
                    $order_amout = $goods_collocation['preferential'];
                    $result['data']['collocation']    = $collocation; //搭配id
                }
                $list = $goods; //商品信息
            }

        $result['data']['user_integral'] = $userdata['data']['score'];
        $result['data']['list']    = $list; //商品数据

        $result['data']['postage'] = $num; //商品数量
        $result['data']['smallclothes_amout'] = $postage_price; //商品邮费
        $result['data']['order_amout']    = $order_amout; //优惠价格
        $result['data']['original_price'] = $money; //商品价格+邮费价格=最终价格

        $result['status']  = true;
        return $result;
    }
    /**
     * @param $uid 用户id
     * @param array $order 商品数据
     * @param $address_type 地址:0用户地址,1 = 安装店
     * @param $address_id 地址id
     * @param $pay_way 1 = 微信支付
     * @param $integral 0 = 不使用积分,1 = 使用积分
     * @param $use_integral 用户积分
     */
    public static function Orderadd($uid, $order = [], $address = [], $share_id = 0,$use_integral = 0, $cart_id = 0)
    {

        $reslut = [
            'data' => [],
            'msg'  => '',
            'status' => false
        ];

        $goods = $order['data'];
        // dump($goods["list"]);
        // die;
        $reslut['msg'] = '商品信息不存在';
        if (empty($order['data']['list']) || empty($goods['list'][0]['id']))
        {
            return $reslut;
        }
        $order_sn = order_sn();
        $time = time();
        try {
            Db::startTrans();
            // 先审核,用户是不是代理商
            $UserModel   = new UserModel();
            $userdata    = $UserModel->getUserInfo($uid); // 用户信息
            $integral = 0; //积分
            $deduction = 0;
            $pretial = 0; // 优惠
            $ConfigModel = new ConfigModel();
            $interPrice = $ConfigModel->interPrice();
            // $cartlist['data']["interPrice"] = $interPrice;
            $goods['goods_price'] = $goods['original_price'];
            if ($userdata['is_vip'] < 2)
            {
                // 积分抵扣   积分大于商品价格,
                if ($goods['user_integral']*$interPrice >= $goods['original_price'])
                {
                    $integral = $goods['user_integral']*$interPrice - $goods['original_price'];  // 剩余积分
                    // $goods['goods_price'] = bcdiv(1,100,2); //商品支付价格
                    $deduction = $goods['original_price']/$interPrice; // 积分抵扣
                }else{
                    // $goods['goods_price'] = $goods['original_price'] - $goods['user_integral']*$interPrice;
                    $deduction = $goods['user_integral']; // 剩余积分

                }
                Db::name('user')->where('id',$uid)->setField('score',$integral); // 更新积分

                if ($goods['user_integral'] != 0)
                {
                    Db::name('integral')->insertGetId(
                        [
                            'uid'       => $uid,
                            'integral'  => $deduction,
                            'type'      => 6,
                            'create_time'   =>$time,
                            'is_type'   =>2,
                        ]
                    );
                }

            }
            if ($goods['collocation'])
            {
                $pretial = Db::name('goods_collocation')->where('id',$goods['collocation'])->value('preferential');
            }

            $data = [
                'uid'      => $uid,
                'order_sn' => $order_sn, // 内部订单号
                'name'     => $address['name'],
                'province' => $address['province'],
                'city'     => $address['coty'],
                'district' => $address['area'],
                'address'  => $address['address'],
                'mobile'   => $address['phone'],
                'goods_price' => $goods['original_price'], //商品总价
                'goods_num'   => $goods['postage'],         //商品数量
                'goods_pay_price' => empty($goods['goods_price']) ? $goods['original_price'] : $goods['goods_price'], //商品数量
                'goods_integral'  => $deduction, //积分抵扣
                'goods_preferential'=> $pretial, //优惠
                'shipping_price'  => $goods['smallclothes_amout'], //运费
                'refund_amount'   => empty($goods['goods_price']) ? $goods['original_price'] : $goods['goods_price'], //运费
                'create_time'     => $time,
                'user_status'     => $userdata['is_vip'],
                'is_shop'         => $address['is_shop'],
                'collocation_id'  => empty($goods['collocation']) ? 0 : $goods['collocation'],
                'share'           => $share_id,
                'delivery_type'   => $goods['freight'],
            ];
            $order_id = Db::name('order')->insertGetId($data);

            $order_goods = [];
            $num = count($goods['list']);
            $goodsNum = 0;
            foreach ($goods['list'] as $key => $val)
            {

                if ($deduction >= $val['zong_price'])
                {
                    $deduction = $deduction - $val['zong_price'];
                    $integral_goods = $val['zong_price'];  //抵扣积分
                    $price = 0; // 当前商品价格就是 0
                    $goodsNum += 1;
                    if ($goodsNum == $num)
                    {
                        $price = 0.01;
                    }
                }else{
                    $price = $val['zong_price'] - $deduction; // 商品价格
                    $integral_goods = $deduction; //抵扣积分
                    $deduction = 0;
                }

                $order_goods = [
                    'order_id' => $order_id,
                    'goods_image' => $val['main_image'],
                    'goods_id' => $val['id'],
                    'sku_id'   => empty($val['sku_id']) ? '' :$val['sku_id'],
                    'create_time' => $time,
                    'goods_name'  => $val['name'],
                    'partnumber'  => $val['partnumber'],
                    'name_keyword'  => $val['goods_number'],
                    'goods_num'   => $val['num'],
                    'goods_price' => $val['price'],
                    'goods_num_price' => $val['zong_price'],
                    'discounts'   => $integral_goods,
                    'price'       => $price,
                    'is_comment'    => 0,
                    'refund_status' => 0,
                ];
                
                Db::name('order_goods')->insertGetId($order_goods);
                Db::name('goods')->where('id',$val['id'])->setDec('stock', $val['num']);
                Db::name('goods')->where('id',$val['id'])->setInc('sales', $val['num']);
            }

            if ($share_id) // 用户分享的走这
            {

                // 判断分享的,跟推荐人是不是一个人
                $share_user    = $UserModel->getUserInfo($share_id);

                if ($userdata['data']['yid'] != $share_id)
                {
                    if ($share_user['is_vip'] > $userdata['is_vip'])
                    {
                        $UserModel->usersell($share_user,$goods['list'],$uid,$order_id, $type = 1);
                    }elseif ($share_user['is_vip'] == $userdata['is_vip']){

                        foreach ($goods['list'] as $key => $val)
                        {
                            $integral = Db::name('goods')->where('id',$val['id'])->value('integral_num');
                            $gid      = $val['id'];
                            $fx_integral = bcmul($integral, $val['num'], 2);
                        }

                        $user_share_data = [
                            'share_id'  => $share_id,
                            'uid'       => $uid,
                            'gid'       => $gid,
                            'share_integral' => $fx_integral,
                            'create_time' => $time,
                            'order_id'    => $order_id,
                            'type'        => 1,
                        ];

                        Db::name('user_share')->insertGetId($user_share_data);
                    }else{
                        echo '没有积分哦';
                    }
                }

            }else{
                // 判断有没有绑定推荐人
                if ($userdata['data']['yid'] && $uid != $userdata['data']['yid'])
                {
                    $yid = $userdata['data']['yid'];
                    $y_user    = $UserModel->getUserInfo($yid); // 2  // 1
                    if ($y_user && $y_user['is_vip'] > $userdata['is_vip'])
                    {
                        $UserModel->usersell($y_user,$goods['list'],$uid,$order_id);
                    }
                }
            }

            if ($order['data']['type'] == 1) // 删除购物车
            {
                Db::name('goods_cart')->where('id', 'in',$cart_id)->where('uid',$uid)->delete();
            }
            Db::commit();
            $reslut['msg'] = '提交成功';
            $reslut['status'] = true;
            $reslut['data'] = $order_id;
        }catch(\Exception $e){
            var_dump($e->getMessage());
            $reslut['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $reslut;
    }


    /**
     * 微信支付商品
     */
    public function Orderpay($uid, $order_id, $pay_way, $type)
    {
        $result = [
            'data' => [],
            'msg'  => '',
            'status' => false
        ];
        // 用户信息
        $UserModel   = new UserModel();
        $user        = $UserModel->getUserInfo($uid);
        if ($type == 'goods')
        {
            $order_id = explode(',',$order_id); // 订单id
            // 订单数据
            $orderlist = [];
            $money = 0;
            foreach($order_id as $v_id)
            {
                $orderdata = Db::name('order')->where('id',$v_id)->find();


                if (!$orderdata)
                {
                    $result['msg'] = '订单不存在';
                    return $result;
                }
                if ($orderdata['pay_status'] != 0)
                {
                    $result['msg'] = $orderdata['order_sn'].'该订单已支付';
                    return $result;
                }
                $orderlist[]  = $orderdata;
                $money += $orderdata['goods_pay_price']; //两个订单总和
            }

            Db::startTrans();
            try {
                $order_pay_sn = order_pay_sn(); // 发给微信的内部单号
                $order_money = [
                    'uid' => $uid,
                    'order_sn'    => $order_pay_sn,
                    'create_time' => time(),
                    'money'       => $money,
                    'type'        => $type
                ];
                // 添加支付数据
                Db::name('order_pay_money')->insert($order_money);

                foreach ($order_id as $oid_v)
                {
                    // 修改订单里面的 微信单号
                    Db::name('order')->where('id',$oid_v)->setField('pay_sn',$order_pay_sn);
                }

                if ($pay_way == 1)
                {
                    $Wxapy = new Wechat();
                    // 微信支付
                    $res = $Wxapy->index($order_pay_sn, $money, '购买商品', $user['data']['openid'], 'order_wx_notify_url');
                    if ($res)
                    {
                        Db::commit();
                        $result['status'] = true;
                        $result['msg'] = '成功';
                        $result['data'] = $res;
                    }else{
                        Db::rollback();
                        $result['msg'] = '失败';
                        $result['status'] = false;
                    }
                }
            }catch(\Exception $e)
            {
                Db::rollback();
                var_dump($e->getMessage());
                $result['status'] = false;
            }

            return $result;
        }elseif ($type == 'money'){
            $order = Db::name('user_order')->where('id',$order_id)->find();
            if (!$order)
            {
                $result['msg'] = '充值订单不存在';
                return $result;
            }
            if ($order['status'] == 1)
            {
                $result['msg'] = '该订单已支付';
                return $result;
            }

            try {
                $order_pay_sn = order_pay_sn();
                $order_money = [
                    'uid'         => $uid,
                    'order_sn'    => $order_pay_sn,
                    'create_time' => time(),
                    'money'       => $order['price'],
                    'type'        => $type
                ];
                $order_moneyId = Db::name('order_pay_money')->insertGetId($order_money);

                if ($order_moneyId)
                {
                    Db::name('user_order')->where('id',$order_id)->setField('pay_sn',$order_pay_sn);
                }

                $Wxapy = new Wechat();
                $res = $Wxapy->index($order_pay_sn, $order['price'], '充值余额', $user['data']['openid'], 'gold_wx_notify_url');
                Db::commit();
                $result['status'] = true;
                $result['msg']    = '支付成功';
                $result['data']   = $res;
            }catch (\Exception $e){
                Db::rollback();
                var_dump($e->getMessage());
                file_put_contents('1.txt','行数:'.$e->getLine().'错误信息:'.$e->getMessage());
                $result['msg'] = '支付失败';
            }
        }else{
            $result['msg'] = '缺少参数了,充值失败';
        }
        return $result;
    }
    /**
     * 充值金币
     */
    public static function Orderuser($uid, $id)
    {
        $result = [
            'data'   => [],
            'status' => false,
            'msg'    => ''
        ];
        $UserModel = new UserModel();
        $user = $UserModel->getUserInfo($uid);
        if (!$user['data'] || $user['data']['is_status']) {
            $result['msg'] = '用户不存在请联系管理员';
            return $result;
        }

        if ($user['is_vip'] != 2 && $user['is_vip'] != 3)
        {
            $result['msg'] = '无法充值请联系管理员';
            return $result;
        }
        $user_id = $user['data']['id'];
        $ConfigModel = new ConfigModel($user_id);
        $Config = $ConfigModel->Getuserprice($user_id);

        $time = time();
        if (array_key_exists($id, $Config))
        {
            $order_sn = order_sn($type = 'gold');
            $price = $Config[$id];
            $data = [
                'uid' => $user_id,
                'order_sn' => $order_sn,
                'create_time' => $time,
                'price' => $price
            ];
            $order_id = Db::name('user_order')->insertGetId($data);
            $result['data'] = $order_id;
            $result['msg'] = '提交订单';
            $result['status'] = true;
        }else{
            $result['msg'] = '充值余额不匹配';
        }

        return $result;
    }
    /**
     * 金币支付
     */
    // 修改状态

//     修改
    public function Orderglod($uid, $order_id)
    {
        $result = [
            'data' => [],
            'msg'  => '',
            'status' => false
        ];
        $UserModel = new UserModel();
        $user = $UserModel->getUserInfo($uid);
        if ($user['is_vip'] < 2)
        {
            $result['msg'] = '您不是代理商';
            return $result;
        }

        $orderid = explode(',', $order_id);
        $order = [];
        $money = 0;
        foreach($orderid as $oid){
            $res = Db::name('order')->where('id',$oid)->find();
            if ($res['order_status'] == 1)
            {
                $result['msg'] = $res['order_sn'].'该订单已支付';
                return $result;
            }
            Db::name('order')->where('id',$oid)->setField('pay_price',$res['goods_pay_price']);
            Db::name('order')->where('id',$oid)->setField('refund_amount',$res['goods_pay_price']);
            $money += $res['goods_price'];
        }
//        $money 总金额
        if ($user['data']['money'] < $money)
        {
            $result['msg'] = '余额不足';
            return $result;
        }

        $time = time();
        Db::startTrans();
        try{

            $order_pay_sn = order_pay_sn();

            foreach($orderid as $id_val)
            {
                Db::name('order')->where('id',$id_val)->setField('pay_sn',$order_pay_sn);
                Db::name('order')->where('id',$id_val)->setField('order_status',1);
            }

            $user_money = bcsub($user['data']['money'], $money, 2);

            $user_money_deta = [
                'uid'     => $uid,
                'money'   => $money,
                'type'    => 'consumption',
                'create_time' => time(),
                'is_type' => 2,
            ];

            $res = Db::name('user_money')->insertGetId($user_money_deta);

            if (!$res)
            {
                echo '支付失败了';
            }

            Db::name('user')->where('id',$uid)->setField('money',$user_money);

            $price = 0;
            foreach($orderid as $key => $val)
            {
                $order_goods = Db::name('order_goods')->where('order_id',$val)->select();

                foreach ($order_goods as $goods_key => $goods_val)
                {

                    Db::name('order_goods')->where('id',$goods_val['id'])->setField('price',$goods_val['goods_price']);
                    $price += $goods_val['goods_price'];
                }

            }

            if ($price > $money)
            {
                Db::rollback();
                $result['msg'] = '金额不足';
                $result['status'] = false;
            }else{
                $pay_out_sn_ = pay_out_sn_();
                $data_order = [
                    'uid'        =>  $uid,
                    'order_sn'   =>  $order_pay_sn,
                    'pay_sn'     =>  $pay_out_sn_,
                    'create_time'  =>  $time,
                    'money'      =>  $money,
                    'type'       =>  'goods',
                    'status'     =>  1,
                    'pay_type'   =>  1
                ];
                $order_pay_money_id = Db::name('order_pay_money')->insertGetId($data_order);
                if ($order_pay_money_id)
                {
                    $data = [
                        'order_status' => 1,
                        'pay_status'   => 1,
                        'pay_way'      => 2,
                        'pay_time'     => $time,
                        'update_time'  => $time,
                        'pay_out_sn'   => $pay_out_sn_,
                    ];
                    Db::name('order')->where('pay_sn',$order_pay_sn)->update($data);
                    $result['msg']    = '操作成功';
                    $result['status'] = true;
                    Db::commit();
                }
            }




        }catch(\Exception $e){
            dump($e->getMessage());
            $getmessage = '金币支付:'.'wenjian:'.$e->getFile().'行数:'.$e->getLine().'错误:'.$e->getMessage();
            file_put_contents('2.txt',$getmessage);
            Db::rollback();
            $result['msg'] = '操作失败';
            $result['status'] = false;
        }

        return $result;
    }

    /**
     * @param $name 商品关键字,零件号,订单编号
     * @param $type 类型:0全部.1待付款.2待发货.3待收货.4待评价.5已完成, 6退款
     * @param $uid
     */
    public static function OrderList($name, $type, $uid)
    {
        if (!$uid) return false;
        $where = [];

        if (!empty($name))
        {
            $where['og.goods_name|og.partnumber|og.name_keyword'] = ['like','%'.$name.'%'];
        }
        $status = []; // 订单状态
        switch ($type)
        {
            case 6:
                $status['order_status'] = ['eq',0]; //待付款
                break;
            case 1:
                $status['order_status'] = ['eq',1];// 代发货
                break;
            case 2:
                $status['order_status'] = ['eq',2]; //待收货
                break;
            case 3:
                $status['order_status'] = ['eq',3]; //待评价
                break;
            case 4:
                $status['order_status'] = ['eq',4]; // 已完成
                break;
            case 5:
                $status['order_status'] = array(['eq',5],['eq',6],'or');//退款
                break;
        }
        $order = Db::name('order')
            ->field('id,order_sn,order_status,pay_status,goods_num,goods_pay_price,shipping_status')
            ->where('uid',$uid)
            ->where('del',0)
            ->where($status)
            ->order('id desc')
            ->select();
        foreach ($order as $key => $val) {
            $order_goods = Db::name('order_goods')
                ->alias('og')
                ->join('goods_item gi','gi.id = og.sku_id','LEFT')
                ->field('og.id,og.goods_name,gi.spec_value_str,og.goods_num,og.price,og.is_comment,og.goods_image,og.refund_status')
                ->where('og.order_id',$val['id'])
                ->where($where)
                ->select();
            if ($order_goods)
            {
                $order[$key]['goods'] = $order_goods;
            }else{
                unset($order[$key]);
            }
        }

        $order = array_values($order);
        return $order;
    }
    /**
     * @param $id 订单id
     * @param $address_id 地址id
     * @param int $type 类型
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function upaddress($id, $address_id, $type = 0)
    {
        if (empty($id) || empty($address_id))
        {
            echo '缺少参数';
            return false;
        }
        if ($type == 1)
        {
            $address = Db::name('user_address')->where('id',$address_id)->find();
            if (!$address)
            {
                echo '地址不存在,请从新添加';
                return false;
            }
            $orderdata = [
                'name'     => $address['shop_name'],
                'province' => $address['province'],
                'city'     => $address['city'],
                'district' => $address['area'],
                'address'  => $address['address'],
                'mobile'   => $address['phone'],
            ];
        }else{
            $address = Db::name('user_address')->where('id',$address_id)->find();
            if (!$address)
            {
                echo '地址不存在,请从新添加';
                return false;
            }
            $orderdata = [
                'name'     => $address['name'],
                'province' => $address['province'],
                'city'     => $address['coty'],
                'district' => $address['area'],
                'address'  => $address['address'],
                'mobile'   => $address['phone'],
            ];
        }

        $response = Db::name('order')->where('id',$id)->update($orderdata);

        if ($response)
        {
            return true;
        }else{
            echo '信息不存在';
            return false;
        }
    }
    /**
     * @param $money  支付金额
     * @param $order_pay_sn 支付单号
     * 商品余额支付
     */
    public function goodsMoney($money,$order_pay_sn,$uid)
    {
        $order = Db::name('order_pay_money')->where('order_sn',$order_pay_sn)->find();
        if (!$order)
        {
            echo '订单未找到';
            return false;
        }

        if ($order['status'] == 1)
        {
            echo '订单已支付';
            return false;
        }

        Db::startTrans();
        try{
            $UserModel = new UserModel();
            $user = $UserModel->getUserInfo($uid);
            $time = time();
            // 剩余余额
            $money = bcsub($user['data']['money'], $order['money'],2);

            $user_money_ = [
                'uid'   => $uid,
                'money' => $order['money'],
                'type'  => 'consumption',
                'create_time' => $time,
                'is_type'  => 2,
            ];
            Db::name('user_money')->insertGetId($user_money_);  // 添加消费记录

            Db::name('user')->where('id',$uid)->update(['money' => $money, 'updatetime' => $time]); // 更新账号余额

            // 修改订单信息
            $pay_out_sn_ = pay_out_sn_();
            $order_pay_sn_data = [
                'pay_sn' => $pay_out_sn_,
                'status' => 1,
                'update_time' => $time,
            ];
            $order_pay_money = Db::name('order_pay_money')->where('order_sn',$order_pay_sn)->update($order_pay_sn_data); // 更新数据
            $order_data = [
                'order_status' => 1,
                'pay_status'   => 1,
                'pay_way'      => 1,
                'pay_time'     => $time,
                'update_time'  => $time,
                'pay_out_sn'   => $pay_out_sn_,
                'user_status'  => $user['data']['is_vip']
            ];

            Db::name('order')->where('pay_sn',$order_pay_sn)->update($order_data); // 更新订单数据
            Db::commit();
            $res = true;
        }catch(\Exception $e){
            Db::rollback();
            var_dump($e->getMessage());
            $res = false;
        }

        return $res;
    }
    /**
     * 取消订单
     * @param $id 订单id
     * @param $uid 用户id
     */
    public static function cancel($id, $uid)
    {
        $result = [
            'msg'    => '',
            'status' => false,
            'data'   => [],
        ];
        $order = Db::name('order')->where('id',$id)->where('uid',$uid)->find();
        if (!$order)
        {
            $result['msg'] = '该订单不存在';
            return $result;
        }

        if ($order['order_status'] == 1 || $order['pay_status'] == 1)
        {
            $result['msg'] = '订单已支付,无法取消';
            return $result;
        }

        try {
            Db::startTrans();


            if ($order)
            {
                $order_goods = Db::name('order_goods')->where('order_id',$order['id'])->delete();
                $user_share  = Db::name('user_share')->where('order_id',$order['id'])->delete();

                if ($order['goods_integral'] != 0)
                {
                    $score = Db::name('user')->where('id',$uid)->value('score');
                    $integral = $score + $order['goods_integral'];
                    Db::name('user')->where('id',$uid)->setField('score',$integral);
                }
                $res = Db::name('order')->where('id',$id)->where('uid',$uid)->delete();
                if ($res){
                    Db::commit();
                    $result['msg']    = '操作成功';
                    $result['status'] = true;
                }else{
                    Db::rollback();
                    $result['msg']    = '取消失败';
                }

            }
        }catch(\Exception $e){
            Db::rollback();
            $result['msg'] = $e->getMessage();
        }
        return $result;

    }
    /**
     * 提醒发货
     * @param $id 订单id
     * @param $uid 用户id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function remind($id, $uid)
    {
        $result = [
            'msg'    => '',
            'status' => false,
            'data'   => [],
        ];
        $order = Db::name('order')->where('id',$id)->where('uid',$uid)->find();
        if (!$order)
        {
            $result['msg'] = '该订单不存在';
            return $result;
        }

        if ($order['order_status'] == 0 || $order['pay_status'] == 0)
        {
            $result['msg'] = '请先支付订单';
            return $result;
        }

        if ($order['remind'] == 1)
        {
            $result['msg'] = '已帮您催促,无需重复操作';
            return $result;
        }


        try {
            Db::startTrans();
            $res = Db::name('order')->where('id',$id)->where('uid',$uid)->update(['remind' => 1]);

            if ($res)
            {
                Db::commit();
                $result['msg']    = '已帮您提醒';
                $result['status'] = true;
            }
        }catch(\Exception $e){
            Db::rollback();
            $result['msg'] = $e->getMessage();
        }
        return $result;

    }
    /**
     * @param $id 订单id
     * @param $uid  用户id
     * @param $lng  经度
     * @param $lat  纬度
     * @return false
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public static function getorder($id, $uid, $lng, $lat)
    {

        $order = Order::where('id',$id)
            ->field('id,order_status,pay_status,name,province,city,district,address,
            mobile,delivery_type,shipping_price,goods_integral,order_sn,create_time,goods_num,goods_pay_price,is_shop')
            ->where('uid',$uid)
            ->find();
        $ConfigModel = new ConfigModel();
        $interPrice   = $ConfigModel->interPrice(); //普通代理商
        $order["goods_integral"] = number_format($order["goods_integral"]*$interPrice,2);
        if (!$order)
        {
            return false;
        }

        $goods = Db::name('order_goods')
            ->alias('g')
            ->join('goods go','go.id = g.goods_id')
            ->join('goods_item it', 'it.id = g.sku_id', 'LEFT')
            ->field('g.id,go.freight,go.free_shipping,g.refund_status,g.goods_id,g.sku_id,g.goods_name,g.goods_num,g.goods_price,g.is_comment,it.spec_value_str,g.goods_image')
            ->where('g.order_id',$order['id'])
            ->select();
        if (!$goods)
        {
            return false;
        }

        $shop = Db::name('user_shop')
            ->field("id,shop_name,shop_images,phone,credit_score, (6378.138 * 2 * asin(sqrt(pow(sin(( lat * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos( lat * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(( lng * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance")
            ->order('distance asc')
            ->find();

        if($order['is_shop'] == 1)
        {
            // 查找安装店
            $shop = Db::name('user_shop')
                ->field("id,shop_images,shop_name,phone,credit_score, (6378.138 * 2 * asin(sqrt(pow(sin(( lat * pi() / 180 - {$lat} * pi() / 180) / 2),2) + cos( lat * pi() / 180) * cos({$lat} * pi() / 180) * pow(sin(( lng * pi() / 180 - {$lng} * pi() / 180) / 2),2))) * 1000) as distance")
                ->where('phone',$order['mobile'])
                ->find();
        }
        $shop['shop_images'] = explode(',',$shop['shop_images'])[0];
        $data = [
            'order' => $order, // 订单
            'goods' => $goods, // 订单
            'shop'  => $shop, //安装店
        ];
        return $data;
    }
    /**
     * 确认收货
     * @param $uid 用户ID
     * @param $id   订单ID
     */
    public static function take_goods($uid, $id)
    {
        $result = [
            'data'   => [],
            'msg'    => '',
            'status' => false,
        ];
    
        $order = Db::name('order')
            ->where('uid',$uid)
            ->where('id',$id)
            ->find();

        if (!$order)
        {
            $result['msg'] = '该订单不存在';
            return $result;
        }

        if ($order['order_status'] == 0)
        {
            $result['msg'] = '订单未付款';
            return $result;
        }
        if ($order['order_status'] == 1)
        {
            $result['msg'] = '该订单还未发货哦';
            return $result;
        }
        $time = time();
        try {
            Db::startTrans();
            $upOrder = [
                'order_status'  => 3,
                'confirm_take_time'  => $time,
                'update_time'   => $time,
            ];
            $res_order = Db::name('order')
                ->where('id',$order['id'])
                ->update($upOrder);
            if ($res_order)
            {
                $share = Db::name('user_share')->where('uid',$uid)->where('order_id',$order['id'])->find();
                if ($share && $share['status'] == 0)
                {
                    Db::name('user_share')->where('id',$share['id'])->setField('status',1);
                    // 分享者用户
                    $UserModel  = new UserModel();
                    $share_user = $UserModel->getUserInfo($share['share_id']);

                    if ($share['type'] == 0)
                    {
                        if ($share_user['is_vip'] == 2 || $share_user['is_vip'] == 3)
                        {
                            $money = bcadd($share_user['data']['money'], $share['share_integral']);
                            Db::name('user')->where('id',$share['share_id'])->setField('money', $money);

                            $user_money_data_ = [
                                    'uid'     => $share['share_id'],
                                    'money'   => $share['share_integral'],
                                    'type'    => 'commission',
                                    'create_time'  => $time,
                                    'is_type' => 1,
                            ];
                            Db::name('user_money')->insertGetId($user_money_data_);
                        }else{
                            $money = bcadd($share_user['data']['score'], $share['share_integral']);
                            Db::name('user')->where('id',$share['share_id'])->setField('score', $money);
                            $user_integral_data_ = [
                                'uid'     => $share['share_id'],
                                'integral'=> $share['share_integral'],
                                'type'    => 4,
                                'create_time'  => $time,
                                'is_type' => 1,
                            ];
                            Db::name('integral')->insertGetId($user_integral_data_);
                        }
                    }else{

                        if ($share_user['is_vip'] == 2 || $share_user['is_vip'] == 3)
                        {
                            $money = bcadd($share_user['data']['money'], $share['share_integral']);
                            Db::name('user')->where('id',$share['share_id'])->setField('money', $money);

                            $user_money_data_ = [
                                'uid'     => $share['share_id'],
                                'money'   => $share['share_integral'],
                                'type'    => 'share',
                                'create_time'  => $time,
                                'is_type' => 1,
                            ];
                            Db::name('user_money')->insertGetId($user_money_data_);
                        }else{
                            $score = bcadd($share_user['data']['score'], $share['share_integral']);
                            Db::name('user')->where('id',$share['share_id'])->setField('score', $score);
                            $user_integral_data_ = [
                                'uid'     => $share['share_id'],
                                'integral'=> $share['share_integral'],
                                'type'    => 3,
                                'create_time'  => $time,
                                'is_type' => 1,
                            ];
                            Db::name('integral')->insertGetId($user_integral_data_);
                        }

                        $user = $UserModel->getUserInfo($uid);
                        $score = bcadd($user['data']['score'], $share['share_integral']);
                        Db::name('user')->where('id',$uid)->setField('score', $score);
                        $user_integral_data_ = [
                            'uid'     => $uid,
                            'integral'=> $share['share_integral'],
                            'type'    => 3,
                            'create_time'  => $time,
                            'is_type' => 1,
                        ];
                        Db::name('integral')->insertGetId($user_integral_data_);
                    }

                }
                Db::commit();
                $result['msg']    = '已收货';
                $result['status'] = true;
            }

        }catch (\Exception $e){
            Db::rollback();
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }
    /**
     * 普通用户退款
     */
    public function refund($uid, $id, $response = [],$cause)
    {
        $result = [
            'data' => [],
            'msg'  => '',
            'status' => false
        ];
        $time = time();
        try {
            // out_refund_no 退款单号
            $order = Db::name('order')->where('id',$id)->find();
            if ($order)
            {
                $UPDATE = [
                    'order_status' => 5,
                    'pay_status'   => 2,
                    'refund'       => 1,
                    'update_time'  => $time
                ];
                Db::name('order')->where('id',$id)->update($UPDATE);
                $order_goods = Db::name('order_goods')->where('order_id',$id)->select();
                Db::name('order_goods')->where('order_id',$id)->where('refund_status',0)->update(['refund_status' => 3]);

                foreach($order_goods as $key => $val){
                    $order_data = [
                        'refund_sn' => $order['order_sn'],
                        'user_id' => $uid,
                        'order_id' => $val['order_id'],
                        'order_goods_id' => $val['id'],
                        'goods_id' => $val['goods_id'],
                        'item_id'  => $val['sku_id'],
                        'goods_num' => $val['goods_num'],
                        'refund_price' => $val['goods_num_price'],
                        'status' => 6,
                        'create_time' => $time,
                        'refund_reason' => $cause
                    ];

                    if ($val['sku_id'] == 0)
                    {
                        Db::name('goods')->where('id',$val['goods_id'])->setInc('stock', $val['goods_num']);
                        Db::name('goods')->where('id',$val['goods_id'])->setDec('sales', $val['goods_num']);
                    }else{
                        Db::name('goods_item')->where('id',$val['goods_id'])->setInc('stock', $val['goods_num']);
                        Db::name('goods_item')->where('id',$val['goods_id'])->setDec('sales', $val['goods_num']);
                    }
                    Db::name('order_sale')->insertGetId($order_data);
                }

                $data = [
                    'uid'           => $uid,
                    'order_id'      => $id,
                    'refund_sn'     => $response['out_refund_no'],
                    'refund_price'  => $order['goods_pay_price'],
                    'refund_amount' => $order['goods_pay_price'],
                    'refund_status' => 1,
                    'refund_way'    => (int)0,
                    'wechat_refund_id'=> $response['refund_id'],
                    'refund_msg'      => $response['return_msg'],
                    'create_time'     => $time,
                    'refund_integral' => $order['goods_integral'],
                    'order_goods'     => 0
                ];
                Db::name('order_refund')->insertGetId($data);

                $user      = Db::name('user')->where('id',$uid)->find();
                $price     = $user['price_sum'] - $order['goods_price'];
                $goods_num = $user['unit_number'] - $order['goods_num'];
                $number    = $user['number'] - 1;
                $score     = $user['score'] + $order['goods_integral'];

                User::update(['id' => $uid, 'score' => $score, 'price_sum'=>$price, 'number' => $number, 'unit_number' => $goods_num]);
                Db::name('integral')->insertGetId(['uid' => $uid, 'integral' => $order['goods_integral'], 'type' => 8, 'create_time' => $time, 'is_type' => 1]);
                $result['status'] = true;
                $result['msg'] = '退款成功';

                Db::commit();
            }else{
                $result['msg'] = '退款失败';
                Db::rollback();
            }
        }catch(\Exception $e){
            var_dump($e->getMessage());
            $result['msg'] = $e->getMessage();
            Db::rollback();
        }

        return $result;


    }
    /**
     * 代理商退款
     */
    public function vip_refund($uid, $id,$order = [],$cause)
    {
        $result = [
            'data' => [],
            'msg'  => '',
            'status' => false
        ];
        if (!$order)
        {
            $result['msg'] = '订单不存在';
            return $result;
        }
        $time = time();
        try {
            $UPDATE = [
                'order_status' => 5,
                'pay_status'   => 2,
                'refund'       => 1,
                'update_time'  => $time
            ];
            Db::name('order')
                ->where('id',$id)
                ->update($UPDATE);
            $order_goods = Db::name('order_goods')->where('refund_status',0)->where('order_id',$id)->select();
            Db::name('order_goods')
                ->where('order_id',$id)
                ->where('refund_status',0)
                ->update(['refund_status' => 3]);

            foreach($order_goods as $key => $val){
                $order_data = [
                    'refund_sn' => $order['order_sn'],
                    'user_id'   => $uid,
                    'order_id'  => $val['order_id'],
                    'order_goods_id' => $val['id'],
                    'goods_id'     => $val['goods_id'],
                    'item_id'      => $val['sku_id'],
                    'goods_num'    => $val['goods_num'],
                    'refund_price' => $val['goods_num_price'],
                    'status'       => 6,
                    'create_time'  => $time,
                    'refund_reason'  =>$cause
                ];
                if ($val['sku_id'] == 0)
                {
                    Db::name('goods')->where('id',$val['goods_id'])->setDec('sales', $val['goods_num']);
                }else{
                    Db::name('goods_item')->where('id',$val['goods_id'])->setDec('sales', $val['goods_num']);
                }
                Db::name('order_sale')->insertGetId($order_data);

            }

            $data = [
                'uid'           => $uid,
                'order_id'      => $id,
                'refund_sn'     => order_sale_sn(),
                'refund_price'  => $order['goods_pay_price'],
                'refund_amount' => $order['goods_pay_price'],
                'refund_status' => 1,
                'refund_way'    => (int)0,
                'wechat_refund_id'=> $order['order_sn'],
                'refund_msg'      => 'OK',
                'create_time'     => $time,
                'refund_integral' => $order['goods_integral'],
            ];
            Db::name('order_refund')->insertGetId($data);
            $user      = Db::name('user')->where('id',$uid)->find();
            $price     = $user['price_sum'] - $order['goods_price'];
            $goods_num = $user['unit_number'] - $order['goods_num'];
            $number    = $user['number'] - 1;
            
            User::update([
                'id'          => $uid,
                'money'       => bcadd($user['money'], $order['pay_price'], 2),
                'price_sum'   =>$price,
                'number'      => $number,
                'unit_number' => $goods_num
            ]);
            Db::name('user_money')->insertGetId([
                    'uid'   => $uid,
                    'money' => $order['refund_amount'],
                    'type'  => 'refund',
                    'create_time' => $time,
                    'is_type'     => 1]
            );
            Db::commit();
            $result['status'] = true;
        }catch (\Exception $e){
            var_dump($e->getMessage());
            $result['msg'] = '支付失败';
            Db::rollback();
        }
        return $result;
    }
    /**
     * 撤销售后
     */
    public function undo($uid, $sale = [])
    {
        try {
            Db::startTrans();
            Db::name('order_sale')->where('id',$sale['id'])->update(['status' => 0, 'del' => 1]);
            Db::name('order_goods')->where('id',$sale['order_goods_id'])->setField('refund_status',0);

            Db::name('order')->where('id',$sale['order_id'])->update(
                [
                    'refund' => 0,
                    'update_time' => time(),
                ]
            );
            $res = true;
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            echo $e->getMessage();
            $res = false;
        }

        return $res;
    }
}